package com.banggood.upms.web;

import com.banggood.silk.web.api.common.PagedResult;
import com.banggood.silk.web.api.exception.SkbException;
import com.banggood.upms.bean.exception.ExceptionEnum;
import com.banggood.upms.bean.po.SystemPo;
import com.banggood.upms.bean.vo.SystemVo;
import com.banggood.upms.bean.vo.search.SysPermSearchCriteria;
import com.banggood.upms.bean.vo.validation.AddGroup;
import com.banggood.upms.bean.vo.validation.UpdateGroup;
import com.banggood.upms.common.component.CommonComponent;
import com.banggood.upms.common.constant.UpmsConstant;
import com.banggood.upms.converter.SystemConverter;
import com.banggood.upms.service.SystemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author XuChuangFeng
 */
@RequestMapping("/sys")
@RestController
@Api(value = "系统管理", description = "系统开发组可以通过添加系统，指定metaUrl来导入系统的权限，也可以同个refreshMeta接口来刷新系统权限。")
public class SystemController {

    @Autowired
    private SystemService systemService;
    @Autowired
    private SystemConverter converter;
    @Autowired
    private CommonComponent commonComponent;

    @RequestMapping(value = "/search", method = RequestMethod.POST)
    @ApiOperation(value = "分页查看系统基本信息", notes = "这个接口暂时不返回系统权限数据，要查看系统权限数据，请调用/perm/search接口。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemId", value = "系统主键，不传入则检索全部系统", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "系统编码", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "是否激活", required = false, paramType = "query", dataType = "String", allowableValues = "ACTIVE,INACTIVE"),
    })
    public PagedResult<SystemVo> search(@Validated({AddGroup.class}) SysPermSearchCriteria criteria) throws Exception {
        PageHelper.startPage(criteria.getPageNum(), criteria.getRows());
        List<SystemPo> systems = systemService.selectByCriteria(criteria);

        //取记录总条数
        long total = new PageInfo<>(systems).getTotal();
        List<SystemVo> permissionVos = converter.outputConverter(systems);
        PagedResult<SystemVo> result = new PagedResult<>(permissionVos, total);
        return result;
    }

    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ApiOperation(value = "根据系统ID获取系统详情", notes = "GET请求")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "系统主键", required = true, paramType = "query", dataType = "String"),
    })
    public SystemVo selectByPrimaryKey(@RequestParam String id) throws Exception {
        SystemPo system = systemService.selectByPrimaryKey(id);
        return system != null ? converter.singleOutputConverter(system) : null;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "增加系统", notes = "POST，会根据metaUrl去拉取对应系统配置的权限数据。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "系统码", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "name", value = "系统名称", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "description", value = "描述", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, paramType = "query", dataType = "String", allowableValues = "ACTIVE,INACTIVE", defaultValue = "ACTIVE"),
            @ApiImplicitParam(name = "metaUrl", value = "同步接口", required = true, paramType = "query", dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 1000, message = "系统code不允许重复!"),
            @ApiResponse(code = 5000, message = "操作失败!")
    })
    public String insert(@Validated({AddGroup.class}) SystemVo inboundSysVo) throws Exception {
        SystemVo systemVo = commonComponent.requestSysPerms(inboundSysVo.getMetaUrl());
        inboundSysVo.setSystemId(commonComponent.generateId());
        SystemVo mergedSys = converter.mergeSysInfoAndPermInfo(inboundSysVo, systemVo);
        SystemPo system = converter.singleInputConverter(mergedSys);
        int count = systemService.insert(system);
        if(count == 0) {
            throw new SkbException(ExceptionEnum.OPERATION_FAILED.getCode(), ExceptionEnum.OPERATION_FAILED.getMessage());
        }
        return UpmsConstant.SUCCESS;
    }

    @RequestMapping(value = "/refresh-meta", method = RequestMethod.GET)
    @ApiOperation(value = "更新系统的权限数据", notes = "必须传入systemId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemId", value = "系统主键", required = true, paramType = "query", dataType = "String"),
    })
    public String refreshMeta(@RequestParam String systemId) throws Exception {
        SystemPo system = systemService.selectByPrimaryKey(systemId);
        SystemVo systemVo = commonComponent.requestSysPerms(system.getMetaUrl());
        if(systemVo != null) {
            systemVo.setSystemId(systemId);
            system.setPermissionList(converter.extractPerms(systemVo));
            systemService.refreshSysPermList(system);
            return UpmsConstant.SUCCESS;
        } else {
            return UpmsConstant.FAILED;
        }
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ApiOperation(value = "删除系统", notes = "必须传入systemId")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemId", value = "系统主键", required = true, paramType = "query", dataType = "String"),
    })
    @ApiResponses({
        @ApiResponse(code = 3001, message = "系统不存在或已被删除！")
    })
    public String deleteByPrimaryKey(@RequestParam String id) throws Exception {
        int count = systemService.deleteByPrimaryKey(id);
        if(count != 1) {
            throw new SkbException(ExceptionEnum.OPERATION_FAILED.getCode(), ExceptionEnum.OPERATION_FAILED.getMessage());
        }
        return UpmsConstant.SUCCESS;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ApiOperation(value = "更新系统的权限数据", notes = "必须传入systemId，传入code并不会更新，而是作为更新条件。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "systemId", value = "系统主键", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "description", value = "描述", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "code", value = "code并不会更新，而是作为更新条件", required = false, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "status", value = "状态", required = false, paramType = "query", dataType = "String", allowableValues = "ACTIVE,INACTIVE", defaultValue = "ACTIVE"),
            @ApiImplicitParam(name = "metaUrl", value = "同步接口", required = false, paramType = "query", dataType = "String"),
    })
    @ApiResponses({
            @ApiResponse(code = 5000, message = "操作失败!")
    })
    public String updateByPrimaryKey(@Validated({UpdateGroup.class}) SystemVo vo) throws Exception {
        int count = systemService.updateByPrimaryKey(converter.singleInputConverter(vo));
        if(count != 1) {
            throw new SkbException(ExceptionEnum.OPERATION_FAILED.getCode(), ExceptionEnum.OPERATION_FAILED.getMessage());
        }
        return UpmsConstant.SUCCESS;
    }
}